package com.njuptB180316.boki.controller;

import com.njuptB180316.boki.dao.UserMapper;
import com.njuptB180316.boki.dataobject.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

@Controller
public class LoginController {

    @Autowired
    private UserMapper userMapper;

    /**
     * 返回登录界面
     */
    @RequestMapping("/login")
    public String login(){
        return "login";
    }

    /**
     * 登录界面
     */
    @RequestMapping("/logininfo")
    public ModelAndView registerinfo(@RequestParam("phone") String phone,
                                     @RequestParam("password") String password,
                                     ModelMap modelMap, HttpServletRequest request){
        User user = userMapper.selectByPrimaryKey(Long.parseLong(phone));
        if (user==null){
            modelMap.addAttribute("msg", "该用户不存在，请重新登录");
            return new ModelAndView("error");
        }else{
            if (!user.getPassword().equals(password)){
                modelMap.addAttribute("msg","用户名或密码错误");
                return new ModelAndView("error");
            }else{
                request.getSession().setAttribute("user", user);//user存入session
                int authority = user.getAuthority();
                if (authority==0){//读者
                    return new ModelAndView("redirect:/");
                }else if (authority==1){//图书管理员
                    return new ModelAndView("redirect:/admin_book");
                }else if(authority==2){//系统管理员
                    return new ModelAndView("redirect:/admin_user");
                }
                return new ModelAndView("index");
            }
        }
    }
}
